package com.googlecode.garbagecan.jmsstudy.openjms;

import java.util.Hashtable;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class TopicSubscribeAsynchronous implements MessageListener {
	private TopicConnection topicConnection;
	private TopicSession topicSession;
	private Topic topic;
	private TopicSubscriber topicSubscriber;

	public static void main(String[] args) {
		new TopicSubscribeAsynchronous();
	}
	
	public TopicSubscribeAsynchronous() {
		try {
			Hashtable properties = new Hashtable();
			properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.exolab.jms.jndi.InitialContextFactory");
			properties.put(Context.PROVIDER_URL, "rmi://localhost:1099/");
			Context context = new InitialContext(properties);

			TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) context.lookup("JmsTopicConnectionFactory");
			topicConnection = topicConnectionFactory.createTopicConnection();

			topicSession = topicConnection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);
			topic = (Topic) context.lookup("topic1");

			topicSubscriber = topicSession.createSubscriber(topic);
			topicSubscriber.setMessageListener(this);
			topicConnection.start();
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	public void onMessage(Message message) {
		try {
			if (message instanceof TextMessage) {
				String messageText = ((TextMessage) message).getText();
				System.out.println(messageText);
			}
		} catch (JMSException ex) {
			ex.printStackTrace();
		}
	}
}
